package com.atguigu.gateway.filter;

import com.atguigu.gateway.util.JwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Base64;
import java.util.UUID;
@Component
public class OnceTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                return chain.filter(exchange).then(Mono.fromRunnable(()->{
                    ServerHttpResponse response = exchange.getResponse();
                    String value = config.getValue();
                    System.out.println("value:"+value);

                    if(value != null && !value.isEmpty()){
                        if ("uuid".equalsIgnoreCase( value)) {
                            value = UUID.randomUUID().toString();
                            System.out.println("uuid:"+value);
                        } else if ("jwt".equalsIgnoreCase(value)) {
                            value = JwtUtil.generateToken("john_doe");
                            System.out.println("jwt:"+value);
                        } else if("base64".equalsIgnoreCase(value)) {
                            value = Base64.getEncoder().encodeToString(value.getBytes());
                            System.out.println("base64:"+value);
                        }

                    }
                    response.getHeaders().add("X-Token",value);
                }));
            }
        };
    }
}
